import { API_SNZO_FILE_URL, API_SNZO_URL } from "../../utils/wxapi";
import { Util } from "../../utils/util";
const wxapi = require("../../utils/wxapi");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    worksItem: null,
    worksItemId: null,
    worksTypeOfData: null,
    addressIndex: 0,
    addressOfData: [],
    params: null,
    isPaying: false,
    isBargainPaying: false,
    showBargain: false,
    snzoImgUrl: API_SNZO_FILE_URL,
    isHandle: false
  },

  /**
   * 获取艺术品详情
   */
  getWorksDetail() {
    wxapi.selectWorksById({ id: this.data.worksItemId }).then(res => {
      if (res.status === 200) {
        this.setData({
          worksItem: res.data
        })
      } else {
        wx.showToast({
          title: '获取数据失败',
          duration: 2000,
          success: () => {
            wx.navigateBack();
          }
        })
      }
    })
  },

  /**
   * 获取收货地址
   */
  getUserAddress() {
    const headers = {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    };
    const bodyparams = {
      cardNo: app.globalData.userInfo.cardNo
    }
    wxapi.getUserAddress(bodyparams, headers).then(res => {
      if (res.code === 20000) {
        this.setData({
          addressOfData: res.data
        })
      }
    })
  },

  /**
   * 选择收货地址
   * @param {*} index 
   */
  chooseAddress(e) {
    const addressIndex = e.currentTarget.dataset.addressIndex;
    this.setData({
      addressIndex
    })
  },

  /**
   * 取消艺术品交易
   */
  cancelPay() {
    wx.switchTab({
      url: '/pages/shop/shop',
    })
  },

  /**
   * 支付前验证
   */
  payAuthFee(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const payType = e.currentTarget.dataset.payType;
    if (payType == 2) {
      this.setData({
        isPaying: true
      })
    } else {
      this.setData({
        isBargainPaying: true
      })
    }

    wx.showLoading({
      title: '支付中',
    })
    const params = {
      worksId: this.data.worksItem.tabStnumWorksMsg.id,
      stk: app.globalData.userInfo.cardNo,
      dealType: payType
    }
    wxapi.buyBeforeVerify(params).then(res => {
      wx.hideLoading();
      if (res.status === 200) {
        const openId = wx.getStorageSync('openId');
        if (openId) {
          this.data.params = Object.assign(params, { openId });
        } else {
          wx.login({
            success: (res) => {
              if (res.code) {
                const jsCode = res.code;
                const headers = {
                  'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                }
                wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                  if (res.code === 20000) {
                    if (res.data) {
                      wx.setStorageSync('openId', res.data);
                      this.data.params = Object.assign(params, { openId: res.data });
                    } else {
                      this.data.isHandle = false;
                      wx.hideLoading()
                      this.setData({
                        isPaying: false,
                        isBargainPaying: false
                      })
                      wx.showToast({
                        title: '获取openId失败',
                        icon: 'error'
                      })
                    }
                  } else {
                    this.data.isHandle = false;
                    wx.hideLoading();
                    wx.showModal({
                      title: '提示信息',
                      content: res.message,
                      showCancel: false
                    })
                  }
                })
              } else {
                this.data.isHandle = false;
                wx.showToast({
                  title: '登录失败',
                  icon: 'error',
                  success: () => {
                    this.setData({
                      isPaying: false,
                      isBargainPaying: false
                    })
                    wx.switchTab({
                      url: '/pages/index/index',
                    })
                  }
                })
              }
            },
          })
        }
        if (payType == 2) {
          wx.showModal({
            title: '提示信息',
            content: '是否确认购买该艺术品？',
            complete: (res) => {
              if (res.cancel) {
                this.data.isHandle = false;
                this.setData({
                  isPaying: false,
                  isBargainPaying: false
                })
              }
              if (res.confirm) {
                this.wxPay();
              }
            }
          })
        } else if (payType == 4) {
          this.setData({
            showBargain: true
          })
        }
      } else {
        this.data.isHandle = false;
        this.setData({
          isPaying: false,
          isBargainPaying: false
        })
        wx.showModal({
          title: '提示信息',
          content: res.msg || res.message,
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack(1);
            }
          }
        })
      }
    })
  },

  /**
   * 议价支付
   * @param {*} e 
   */
  bargainPay(e) {
    const bargainValue = e.detail.bargainInfo;
    if (!bargainValue.bargaining) {
      wx.showToast({
        title: '请填写议价价格',
        icon: 'error'
      })
      return;
    }
    if (bargainValue.bargaining < 10) {
      wx.showModal({
        content: '议价价格不能低于10元',
        showCancel: false
      })
      return;
    }
    if (bargainValue.bargaining > this.data.worksItem.tabStnumWorksMsg.worksPrice) {
      wx.showModal({
        content: '议价价格不能超过该艺术品的原价',
        showCancel: false
      })
      return;
    }
    this.data.params = Object.assign(this.data.params, Util.trimNulls(bargainValue));
    this.wxBargainPay();
  },

  /**
   * 立即支付购买艺术品
   */
  wxPay() {
    const bodyParams = Util.trimNulls(this.data.params);
    wxapi.wxApplyMiniPay(bodyParams, this.data.addressOfData[this.data.addressIndex]).then(res => {
      if (res.status === 200) {
        this.wxPayment(res.data)
      }
    })
  },

  /**
   * 议价支付购买艺术品
   */
  wxBargainPay() {
    const headers = {
      Authorization: app.globalData.token
    }
    const bodyParams = Util.trimNulls(this.data.params);
    wxapi.wxApplyMiniPayBargain(bodyParams, this.data.addressOfData[this.data.addressIndex], headers).then(res => {
      if (res.status === 200) {
        this.wxPayment(res.data)
      }
    })
  },

  /**
   * 唤起微信支付
   */
  wxPayment(data) {
    wx.requestPayment({
      nonceStr: data.nonceStr,
      package: data.packageValue,
      paySign: data.paySign,
      signType: data.signType,
      timeStamp: data.timeStamp,
      success: (res) => {
        this.data.isHandle = false;
        this.setData({
          isPaying: false,
          isBargainPaying: false,
          showBargain: false
        })
        wx.showToast({
          title: '购买成功',
          success: () => {
            wx.navigateTo({
              url: '/pages/center/buylog/buylog',
            })
          }
        })
      },
      fail: (res) => {
        this.data.isHandle = false;
        this.setData({
          isPaying: false,
          isBargainPaying: false,
          showBargain: false
        })
        if (res.errMsg.indexOf('fail cancel') !== -1) {
          wx.showToast({
            title: '交易取消',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '订单数据异常',
            icon: 'error'
          })
        }
      }
    })
  },

  /**
   * 取消支付 隐藏弹窗
   */
  cancelPopup() {
    this.setData({
      isPaying: false,
      isHandle:false,
      isBargainPaying: false,
      showBargain: false
    })
  },

  /**
   * 预览艺术品
   */
  previewImage() {
    const worksItem = this.data.worksItem;
    if (worksItem.tabStnumWorkses[0].standby2.indexOf('image') !== -1 || worksItem.tabStnumWorkses[0].standby2.indexOf('video') !== -1) {
      wx.previewMedia({
        sources: [
          {
            url: this.data.snzoImgUrl + worksItem.tabStnumWorkses[0].standby1,
            type: worksItem.tabStnumWorkses[0].standby2.split('/')[0]
          }
        ],
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel && Object.keys(eventChannel).length > 0) {
      eventChannel.on('worksMsg', (worksMsg) => {
        if (worksMsg) {
          this.setData({
            worksItemId: worksMsg.worksItemId,
            worksTypeOfData: worksMsg.worksTypeOfData
          });
          this.getWorksDetail();
          this.getUserAddress();
        } else {
          wx.switchTab({
            url: '/pages/center/center',
          })
        }
      })
    } else {
      wx.switchTab({
        url: '/pages/center/center',
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})